package com.ojoin.trade.supplyloan_core.web.task;

import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.web.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.Config;
import com.ojoin.trade.common.utils.EmailSendUtil;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.paynow.IAccountConst;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.quartz.CronExpression;
import com.ojoin.trade.common.web.quartz.TaskGroup;
import com.ojoin.trade.common.web.task.BaseQuartzJob;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbRuntaskInfo;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbRuntaskInfoService;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-11-30
 * Time: 下午5:04
 * To change this template use File | Settings | File Templates.
 */

@Component
public class SLLoanTask extends BaseQuartzJob {

    @Autowired
    private TbSlLoanCaculateFeeService caculateFeeService;

    @Autowired
    private TbSlLoanService loanService;

    @Autowired
    private TbSlLoanCreditService creditService;

    @Autowired
    private TbRuntaskInfoService tbRuntaskInfoService;

    @Autowired
    private TbSlProcessInfoService tbSlProcessInfoService;

    @Autowired
    private TbSlLoanApplicationService tbSlLoanApplicationService;
    @Autowired
    private TbSlLoanInfoService tbSlLoanInfoService;

	@Autowired
	private AccountBaseService accountService;
	
	@Autowired
	private TbMerchantInfoBaseService userinfoService;

    private static final Logger logger = LoggerFactory
            .getLogger(SLLoanTask.class);

    @CronExpression(cron="1 0 0 * * ?",desc="供应链自动计息")
    public void caculateFee(){
           try{
               caculateFeeService.updateCaculateFee();
               TbRuntaskInfo info=new TbRuntaskInfo();
               info.setTaskDate(TimeUtils.getCurDate());
               info.setTaskName("计息");
               info.setTaskStatus(IConstDef.RUNTASK_STATUS_SUCCESS);
               info.setTaskTime(TimeUtils.getCurTime());
               info.setTaskType(IConstDef.RUNTASK_TYPE_AUTO);
               tbRuntaskInfoService.insertRuntaskInfo(info);
           }catch (Exception e){
               TbRuntaskInfo info=new TbRuntaskInfo();
               if(e.getMessage().length()<1000){
                   info.setErrorMsg(e.getMessage());
               }else{
               info.setErrorMsg(e.getMessage().substring(0,999));
               }
               info.setTaskDate(TimeUtils.getCurDate());
               info.setTaskName("计息");
               info.setTaskStatus(IConstDef.RUNTASK_STATUS_FAILED);
               info.setTaskTime(TimeUtils.getCurTime());
               info.setTaskType(IConstDef.RUNTASK_TYPE_AUTO);
               tbRuntaskInfoService.insertRuntaskInfo(info);
               LogUtils.info(logger, "计息错误");
               LogUtils.error(logger, e);
           }
    }
    
    @CronExpression(cron="0 0/40 12,15 * * ?",desc="供应链自动还款")
	public void repayLoan() {
		try {
			loanService.execAutomaticRepayLoan(ISLConstDef.AUTO_OPERATOR);
		} catch (Exception e) {
			 LogUtils.info(logger, "自动还款失败");
             LogUtils.error(logger, e);
		}
	}
    
    @CronExpression(cron="0 0/10 12,15 * * ?",desc="生成待还款任务")
    public void queryFinanceInfo(){
         loanService.queryFinanceInfo();
    }
    
    @CronExpression(cron ="0 0 10 * * ?",desc="供应链贷款快到期提醒")
    public  void sendMessage(){
        try{
        creditService.queryNeedMessage();
        }catch (Exception e){
            LogUtils.info(logger, "贷款到期提醒失败");
            LogUtils.error(logger, e);
        }
    }
    @CronExpression(cron  ="0 0 11 * * ?",desc="供应链保理合同快到期提醒")
    public void sendMessageForContractExpire(){
        try{
        tbSlLoanApplicationService.queryNeedMessage();
        }catch (Exception e){
            LogUtils.info(logger, "保理合同到期提醒失败");
            LogUtils.error(logger, e);
        }
    }
    @CronExpression(cron="0 0 1 * * ?",desc="供应链自动取消订单")

    public void cancelCredit(){
      try{
       tbSlProcessInfoService.cancelCredit();
       creditService.updateForCancelCreditLog();
          TbRuntaskInfo info=new TbRuntaskInfo();
          info.setTaskDate(TimeUtils.getCurDate());
          info.setTaskName("自动取消贷款");
          info.setTaskStatus(IConstDef.RUNTASK_STATUS_SUCCESS);
          info.setTaskTime(TimeUtils.getCurTime());
          info.setTaskType(IConstDef.RUNTASK_TYPE_AUTO);
          tbRuntaskInfoService.insertRuntaskInfo(info);
      }catch (Exception e){
    	  LogUtils.info(logger, "自动取消申请贷款失败");
          LogUtils.error(logger, e);
          TbRuntaskInfo info=new TbRuntaskInfo();
          if(e.getMessage().length()<1000){
              info.setErrorMsg(e.getMessage());
          }else{
              info.setErrorMsg(e.getMessage().substring(0,999));
          }
          info.setTaskDate(TimeUtils.getCurDate());
          info.setTaskName("计息");
          info.setTaskStatus(IConstDef.RUNTASK_STATUS_FAILED);
          info.setTaskTime(TimeUtils.getCurTime());
          info.setTaskType(IConstDef.RUNTASK_TYPE_AUTO);
          tbRuntaskInfoService.insertRuntaskInfo(info);
      }
    }
    @CronExpression(cron  ="0 0 18 * * ?",desc="备份商户的贷款情况总表")
    public void copySlLoanInfo(){
        try{
          tbSlLoanInfoService.updateForCopyLoanInfo();
            }catch (Exception e){
            LogUtils.info(logger, "自动备份贷款情况总表失败");
            LogUtils.error(logger, e);
            TbRuntaskInfo info=new TbRuntaskInfo();
            if(e.getMessage().length()<1000){
                info.setErrorMsg(e.getMessage());
            }else{
                info.setErrorMsg(e.getMessage().substring(0,999));
            }
            info.setTaskDate(TimeUtils.getCurDate());
            info.setTaskName("自动备份贷款情况总表");
            info.setTaskStatus(IConstDef.RUNTASK_STATUS_FAILED);
            info.setTaskTime(TimeUtils.getCurTime());
            info.setTaskType(IConstDef.RUNTASK_TYPE_AUTO);
            tbRuntaskInfoService.insertRuntaskInfo(info);
        }
    }
	@Override
	public TaskGroup getTaskGroupName() {
		return TaskGroup.SLLOAN;
	}

    
    @CronExpression(cron ="0 0/1 14,15,16 * * ? *",desc="供应链贷-天津方鑫结算户余额查询")
    public  void queryTJFXBusinessAccountBalance(){
        try {
        	TbMerchantInfo infovo = userinfoService.queryInfoByJoinId(123);
        	String balance = accountService.queryBalance(infovo.getMhtNo(), "AT02");
        	LogUtils.info(logger,"供应链贷-天津方鑫结算户余额：" + balance);
        	if (CommonUtils.getLong(balance) > 0) {
        		String to= "459800285@qq.com";
                String cc=  "guoting@18join.com;wsy@18join.com;lindaxdou@163.com;dgx@18join.com";
            	// 发送内容
            	String msg = "供应链贷-天津方鑫结算户余额：" + CommonUtils.getFenByString(balance) + "元"; 
            	String from = Config.getProperty("mail.from.t1");
            	String fromshortname = "九盈供应链贷业务组";
            	LogUtils.info(logger, "正在发送邮件 收件人:" + to + " 抄送人:" + cc + " 内容:" + msg + "");
            	 
            	boolean isSuccess = EmailSendUtil
            			.sendByAttchByte(from, fromshortname, to,cc, msg, msg, null);
            	if (isSuccess) {
            		LogUtils.info(logger, "邮件发送成功.");
        		} else {
        			LogUtils.info(logger, "邮件发送失败，请检查.");
        		}
        	}
        } catch (Exception e){
            LogUtils.info(logger, "供应链贷-天津方鑫结算户余额查询失败");
            LogUtils.error(logger, e);
        }
    }
    
}